<?php

namespace catchAdmin\externalGoods\service;

use catchAdmin\api\model\Order;
use catchAdmin\customs\model\HnOrderDetail;
use catchAdmin\externalGoods\model\OrderLogistics;
use catchAdmin\product\model\GoodsDescription;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use houniao\api\v1\Goods;
use houniao\api\v1\Order as OrderApi;
use catchAdmin\externalGoods\model\OrderLogisticsTrack as LogisticsModel;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class OrderService{

    protected $user;

    public function __construct()
    {

    }

    //订单状态更新通知
    public function notifyOrderStatusSend($param){

//        {
//            "customs_time":1670653008,
//            "order_no":"2022113009167",
//            "order_status":2,
//            "source_order_no":"20221130191154680153"
//        }
        $orderStatusOptions = [
          -3=>'异常订单',
          -2=>'是待付款',
          -1=>'已取消',
           0=>'待发货',
//           1=>'已发货、待收货',
           1=>'已发货',
           2=>'已收货',
           3=>'海关审核中|仓库分拣打包中',
           5=>'已完成',
        ];

        $order_id = $param['source_order_no'];//来源订单编号
        $push_status = array_key_exists($param['order_status'],$orderStatusOptions) ? $orderStatusOptions[$param['order_status']] : '未知';

        //$insert = [];
        //$orderModel = new Order;

        Db::startTrans();
        try {
            $explode = explode('_', $order_id);
            $main_order_id = $explode[0];//主订单的ID

            if(count($explode) == 3){
                $main_order_id = $explode[0].'_'.$explode[1];
            }

            $orderModel = (new Order)->where('orderId',$main_order_id)->find();
            $orderModel->push_status = $push_status;

            //修改子订单订单状态
            $hnOrderModel = (new HnOrderDetail)->where('source_order_no',$order_id)->find();
            $hnOrderModel->mall_order_status = $param['order_status']; // 处理过的状态
            $hnOrderModel->order_status = $param['order_status']; //上游自由的状态
            $res1 = $hnOrderModel->save();

            $res = $orderModel->save();
            if($res && $res1){
                Db::commit();
            }else{
                throw new Exception('订单状态，保存失败');
            }

            return true;
        } catch (\Exception $exception) {
//            throw new Exception($exception->getMessage());
            Db::rollback();
            return false;
        }
    }
}